<template>
  <!-- 员工 -->
  <div class="employees-container">
    <div class="app-container">
      <page-header>
        <!-- 左侧插槽 -->
        <template #left>
          <div class="left-content">
            <span>总条数:{{ total }}条</span>
          </div>
        </template>
        <!-- 右侧插槽 -->
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/employees/excel')"
          >
            Excel上传
          </el-button>
          <el-button type="danger" size="small" @click="handleDownload"
            >Excel下载当前页</el-button
          >
          <el-button type="success" size="small" @click="handleDownloads"
            >Excel下载全部</el-button
          >
          <el-button type="primary" size="small" @click="isShows = true">
            新增
          </el-button>
        </template>
      </page-header>
      <!-- 新增弹层 -->

      <el-card style="margin-top: 12px" v-loading="loading">
        <el-table :data="employerList" style="width: 100%">
          <el-table-column
            type="index"
            :index="indexMethod"
            label="序号"
            sortable
            width="60"
          >
          </el-table-column>
          <el-table-column label="姓名" prop="username"> </el-table-column>
          <el-table-column label="头像" width="80">
            <template #default="{ row }">
              <el-avatar>
                <img
                  v-image="defaultImgUrl"
                  :src="row.staffPhoto"
                  @click="handleQrCode(row.staffPhoto)"
                />
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile"> </el-table-column>
          <el-table-column label="工号" prop="workNumber" width="80">
          </el-table-column>
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formOfEmployee(+row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName">
          </el-table-column>
          <el-table-column label="入职时间" prop="timeOfEntry">
          </el-table-column>
          <el-table-column label="账户状态" width="80">
            <template #default="{ row }">
              {{ formatEnableState(row.enableState) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="handlePersona(row.id)">
                角色
              </el-button>
              <el-button
                type="text"
                @click="delemployee(row.id)"
                v-permission="'point-del'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="query.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    <add-employee :employeeIsShow.sync="isShows" @Re-render="handleRendering" />
    <el-dialog
      title="二维码"
      :visible="isShowQrCode"
      @close="isShowQrCode = false"
      width="38%"
    >
      <canvas ref="qrCode" />
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible="isShow"
      @close="handleClose"
      width="45%"
      v-loading="loading"
    >
      <el-checkbox-group v-model="checkedRoleList">
        <el-checkbox
          :label="item.id"
          v-for="item in roleLiset"
          :key="item.id"
          >{{ item.name }}</el-checkbox
        >
      </el-checkbox-group>
      <template #footer>
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="handleAssign"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Obj from "@/constant/employees";
import defaultImgUrl from "@/assets/common/user-filling.png";
import AddEmployee from "./components/add-employee.vue";
import {
  getEmployeeListApi,
  deleteEmployeeApi,
  detailEmployeeApi,
  assignmentEmployeeApi,
} from "@/api/employees";
import { getParsonasApi } from "@/api/persona";
// Excel文件的导入导出
// 导入：把Excel文件中的数据读到内存中，
//       读出来就是一个数组，基于数组做列表渲染
import { export_json_to_excel } from "@/vendor/Export2Excel";
import QrCode from "qrcode";
export default {
  name: "ViewsEmployees",
  components: {
    AddEmployee,
  },
  data() {
    return {
      // 用户头像加载失败使用默认头像
      defaultImgUrl,
      // 控制弹层开关
      isShows: false,
      // 获取员工列表
      employerList: [],
      // 获取页数
      query: {
        page: 1,
        size: 5,
      },
      // 页数
      total: 1,
      // 加载
      loading: false,
      // 二维码弹窗
      isShowQrCode: false,
      // 角色弹窗
      isShow: false,
      checkedRoleList: [],
      roleLiset: [],
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 分配角色弹窗打开
    async handlePersona(id) {
      this.id = id;
      this.isShow = true;
      const { data } = await getParsonasApi({ page: 1, pagesize: this.total });
      this.roleLiset = data.rows;
      const resp = await detailEmployeeApi(id);
      this.checkedRoleList = resp.data.roleIds;
    },
    // 分配角色
    async handleAssign() {
      await assignmentEmployeeApi({
        id: this.id,
        roleIds: this.checkedRoleList,
      });
      this.handleClose();
      this.$message.success("分配角色成功");
    },
    // 关闭角色弹窗
    handleClose() {
      this.isShow = false;
    },

    // 展示二维码
    handleQrCode(url) {
      if (!url) return;
      // 显示弹层
      this.isShowQrCode = true;
      // 把点击的图片地址转成二维码
      this.$nextTick(() => {
        console.log(this.$refs.qrCode);
        QrCode.toCanvas(this.$refs.qrCode, url);
      });
    },
    // 获取员工列表
    async getEmployeeList() {
      this.loading = true;
      const { data } = await getEmployeeListApi(this.query);
      // 预处理聘用形式
      this.employerList = data.rows;
      this.total = data.total;
      this.loading = false;
    },
    // 处理条数
    handleSizeChange(val) {
      this.query.size = val;
      this.getEmployeeList();
    },
    // 处理页数
    handleCurrentChange(val) {
      this.query.page = val;
      this.getEmployeeList();
    },
    // 处理序号
    indexMethod(index) {
      return index + 1 + (this.query.page - 1) * this.query.size;
    },
    // 删除员工
    async delemployee(id) {
      try {
        await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 判断 当前页数据只有一个数据时，删除之后显示上一页的数据
        if (this.employerList.length === 1 && this.query.page > 1) {
          this.query.page--;
        }
        await deleteEmployeeApi(id);
        // 重新渲染页面
        this.getEmployeeList();
        this.$message.success("删除成功");
      } catch (error) {
        this.$message.success("取消成功");
      }
    },
    handleRendering() {
      this.getEmployeeList();
    },
    //处理聘用形式
    formOfEmployee(formOfEmployment) {
      const item = Obj.hireType.find((item) => item.id === formOfEmployment);
      return item ? item.value : "未知";
    },
    formatEnableState(enableState) {
      const item = Obj.workingState.find((item) => item.id === enableState);
      return item ? item.value : "未知";
    },
    // 下载Excel
    handleDownload() {
      this.downloadCommunal(this.employerList);
    },
    // 下载全部
    async handleDownloads() {
      const { data } = await getEmployeeListApi({
        page: this.query.page,
        size: this.total,
      });
      this.downloadCommunal(data.rows);
    },
    //复用
    downloadCommunal(data) {
      const headers = [
        "姓名",
        "手机号",
        "入职日期",
        "聘用形式",
        "转正日期",
        "工号",
        "部门",
      ];
      const headersRelations = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };

      const dataArr = data.map((item) => {
        const arr = [];
        headers.forEach((key) => {
          const enkey = headersRelations[key];
          if (enkey === "formOfEmployment") {
            item[enkey] = this.formOfEmployee(+item[enkey]);
          }
          arr.push(item[enkey]);
        });
        return arr;
      });
      // 调用下载excel文件的方法
      export_json_to_excel({
        header: headers,
        data: dataArr,
        filename: `${this.$store.getters.userInfo.companyName}员工信息表`,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>